import { requestURL } from '../utils/config.js'

function getType(data={}, method, header = {'content-type': 'application/x-www-form-urlencoded'}) { // 获取请求方式
	let type = {}
	if (method == 'post') {
		method = 'post'
		type = {
			method,
			data: {
				...data
			},
			header: {
				...header,
				'Authorization': uni.getStorageSync('LOGIN_TOKEN')
			}
		}
	} else {
		// method = 'get'
		type = {
			method,
			data: {
				...data
			},
			header: {
				...header,
				'Authorization': uni.getStorageSync('LOGIN_TOKEN')

			}
		}
	}
	return type
}
function request(url, method, data, header) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: requestURL + url,
			...getType(data, method, header),
			success: res => {
				if (res.statusCode == 200) {
					if(res.data.code==401){
						uni.showToast({
							title:res.data.msg,
							icon:"none",
							duration: 1000
						});
						uni.removeStorageSync("LOGIN_TOKEN")
						setTimeout(()=>{
							uni.reLaunch({
								url:"/pages/loginRegister/loginName"
							})
						},2000)
					}
					resolve(res.data)
				} else {
					if (res.statusCode == 502) {
						uni.showModal({
							title: '',
							content: '网络超时,请稍后打开!',
							showCancel: false
						})
					} else {
						uni.showModal({
							title: '',
							content: res.errMsg,
							showCancel: false
						})
					}
				}
			},
			fail: err => {
				uni.hideLoading()
				console.log('err')
				reject(err)
			},
			complete: function () {
				console.log('complete')
				// uni.hideLoading()
			}
		})
	}).catch(err => {
		console.log(err)
		uni.hideLoading()
	})
}

export default request